<template>
  <div ref="dnd" class="dnd-container" />
</template>

<script>
import { Addon } from "@antv/x6";
import { getGraph } from "../graph-common/graph";

export default {
  methods: {
    init(groups, nodes) {
      const graph = getGraph();
      const stencil = new Addon.Stencil({
        title: "组件库",
        target: graph,
        groups: groups,
        // groups: [
        //   {
        //     name: "group1",
        //     title: "标题1",
        //   },
        //   {
        //     name: "group2",
        //     title: "标题2",
        //   },
        // ],
        search: (cell, keyword) => {
          if (keyword) {
            return (
              cell.shape === "rtNode" &&
              cell.attrs.label.text.includes(keyword)
            );
          }
          return true;
        },
        layoutOptions: {
          columns: 1, //一行一个node
          dx: 10,
          center: false,
          rowHeight: "compact",
        },
        stencilGraphPadding: 0,
        stencilGraphWidth: 220,
        placeholder: "请输入关键字",
        notFoundText: "没有找到相关内容",
      });
      const groupNames = [];

      for (let i = 0; i < groups.length; i++) {
        groupNames.push(groups[i].name);
      }
      const Nodes = {};
      for (let i = 0; i < nodes.length; i++) {
        groupNames.forEach((item) => {
          if (item === nodes[i].group) {
            if (!Nodes[item]) {
              Nodes[item] = [];
            }
            Nodes[item].push(
              graph.createNode({
                shape: "rtNode",

                attrs: {
                  label: {
                    text: nodes[i].text,
                  },
                },
                ports: [
                  {
                    group: "in",
                  },

                  {
                    group: "out",
                  },
                ],
                data: {
                  ...nodes[i].data,
                  icon: nodes[i].icon,
                  text: nodes[i].text,
                },
              })
            );
          }
        });
      }

      for (let key in Nodes) {
        // 将模板节点添加到指定的群组中。
        stencil.load(Nodes[key], key);
      }

      this.$refs.dnd.appendChild(stencil.container);
      stencil.filter("");
    },
  },
};
</script>

<style scoped lang="less">
.dnd-container {
  width: 200px;
  height: 100%;
  position: relative;
  /deep/& > div {
    width: 200px;
  }
}
/deep/ .x6-widget-stencil.not-found.searchable::after {
  top: 120px;
}
/deep/ .x6-widget-stencil-search{
  font-size: 12px;
}
/deep/ .x6-widget-stencil-title,
.x6-widget-stencil-group > .x6-widget-stencil-group-title {
  height: 37px;
}
</style>


